package com.atguigu.baku.service.impl;

import com.atguigu.baku.entity.AreaCity;
import com.atguigu.baku.mapper.AreaCityMapper;
import com.atguigu.baku.service.AreaCityService;
import com.atguigu.baku.vo.AreaCityVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dayouzi
 * @since 2022-11-10
 */
@Service
public class AreaCityServiceImpl extends ServiceImpl<AreaCityMapper, AreaCity> implements AreaCityService {

    @Resource
    private AreaCityMapper areaCityMapper;

    @Override
    public List<AreaCityVo> getAreaCity() {
        //返回结果
        List<AreaCityVo> resultList = new ArrayList<>();

        //获取一级分类
        List<AreaCity> firstList = areaCityMapper.getFirstAreaCity();

        //获取二级分类
        List<AreaCity> secondList = areaCityMapper.getSecondAreaCity();

        firstList.forEach(x -> {
            List<AreaCityVo> areaCityVoList = new ArrayList<>();
            AreaCityVo areaCityVo = new AreaCityVo();
            BeanUtils.copyProperties(x, areaCityVo);
            secondList.stream()
                    .filter(y -> y.getPid().equals(x.getId()))
                    .forEach(y -> {
                        AreaCityVo areaCityVoChild = new AreaCityVo();
                        BeanUtils.copyProperties(y, areaCityVoChild);
                        areaCityVoList.add(areaCityVoChild);
                    });
            areaCityVo.setChildren(areaCityVoList);
            resultList.add(areaCityVo);
        });

        return resultList;
    }
}
